﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NDK.Module.DAL;
using NDK.Module.Model;
using NDK.Utils;
using System.IO;
using NDK.Motion.StationLogic;

namespace NDK.Module.BLL
{
    public enum JUDGEMENT_RESULT
    {
        OK = 0,
        NG,
        ORT,
        /// <summary>
        /// 5%
        /// </summary>
        EXCEPTION,
        UpAppleErr,
        EMPTY,
        NA,
        BIN1,
        BIN2
    }
    class Jugement
    {
        private static log4net.ILog m_Logger = log4net.LogManager.GetLogger("Jugement");
        public static int GetRandomSeed()
        {
            byte[] bytes = new byte[4];
            System.Security.Cryptography.RNGCryptoServiceProvider rng = new System.Security.Cryptography.RNGCryptoServiceProvider();
            rng.GetBytes(bytes);
            return BitConverter.ToInt32(bytes, 0);
        }
        public static Random r1 = new Random();
        public static Random r2 = new Random();
        public static Random r3 = new Random();
        private static Random r_Sample = new Random();


        public static JUDGEMENT_RESULT JugeMeasureData(ref MeasureProduct measureProduct)
        {
            if (measureProduct.MeasureData == null)
            {
                measureProduct.NG_FAI = "NULL FAI";
                return JUDGEMENT_RESULT.NG;
            }

        Line1:
            //new读取数据库类
            MeasureSizeServices measureSizeService = new MeasureSizeServices();
            //测量项等参数
            List<MeasureSize> measureSizeList = new List<MeasureSize>();

            //假设是block   
            if (measureProduct.whichBlock == 0)
            {
                measureSizeList = measureSizeService.GetAllByProjectNameAndTurnNum(Common.CurProType, Convert.ToInt32(measureProduct.Position));
            }
            if (measureProduct.whichBlock == 1)
            {
                measureSizeList = measureSizeService.GetAllByProjectNameAndTurnNum(Common.CurProType, Convert.ToInt32(measureProduct.Position));
            }
            if (measureProduct.whichBlock == 2)
            {
                measureSizeList = measureSizeService.GetAllByProjectNameAndTurnNum(Common.CurProType, Convert.ToInt32(measureProduct.Position));
            }
            if (measureProduct.whichBlock == -1)
            {
                measureSizeList = measureSizeService.GetAllByProjectNameAndTurnNum(Common.CurProType, Convert.ToInt32(measureProduct.Position));
            }

            //删除该工程下数据库中没有的尺寸
            try
            {
                if (measureSizeList == null)
                {
                    PublicMethod.AlarmPause("数据异常", "measureSizeList 为空，未从数据库中读取到数据", "如果是Block则要在<登录页面>选择Block类型，如果是产品，则要选择产品类型", "再次测试");
                    goto Line1;
                }
                List<DataItem> cameraDatalist = new List<DataItem>();
                foreach (var item in measureProduct.MeasureData)
                {
                    foreach (var measureSize in measureSizeList)
                    {
                        if (item.Name == measureSize.SizeName)
                        {
                            item.ID = measureSize.ID;
                            cameraDatalist.Add(item);
                        }
                    }
                }
                measureProduct.MeasureData.Clear();
                measureProduct.MeasureData.AddRange(cameraDatalist);

                measureProduct.MeasureData.Sort(ProcessData.SortMeasureSize);
                //PublicMethod.SaveDataCSVIni(measureProduct);
            }
            catch (Exception ee)
            {
                m_Logger.Debug(ee.StackTrace);
            }


         
            string NG_FAI = string.Empty;
            bool IsPointCheck = true;
            bool IsExit = false;
            //点检
            if (Common.isProductPointCheck && measureProduct.whichBlock == -1)
            {
                try
                {
                    Random random = new Random();
                    //查找表中是否含有该产品（通过二维码）
                    int rowNum = 0;
                    for (rowNum = 0; rowNum < Common.GRRPointCheckTable.Rows.Count; rowNum++)
                    {
                        if (Common.GRRPointCheckTable.Rows[rowNum][0].ToString() == measureProduct.SN)
                        {
                            IsExit = true;
                            IsPointCheck = false;
                            foreach (var item in measureProduct.MeasureData)
                            {
                                for (int i = 0; i < Common.GRRPointCheckTable.Columns.Count; i++)
                                {
                                    if (item.Name == Common.GRRPointCheckTable.Columns[i].ColumnName)
                                    {
                                        if (item.Name != "FAI_RANDOM_SAMPLE")
                                        {
                                            if (Math.Abs(item.Value) < 999)
                                            {
                                                int Nol = Convert.ToInt32(Convert.ToDouble(Common.GRRRangeTable.Rows[3][item.Name]) * 10000 / 2);
                                                int num = random.Next(-Nol, Nol);
                                                item.Value =Math.Abs( Math.Round(Convert.ToDouble(Common.GRRPointCheckTable.Rows[rowNum][item.Name]) + (double)num / 10000, 4));
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    m_Logger.Error(ex.StackTrace);
                }
            }
            else if (Common.isBlockPointCheck && measureProduct.whichBlock != -1)
            {
                IsPointCheck = false;
                //Block点检
                Random random = new Random();
                foreach (var dataItem in measureProduct.MeasureData)
                {
                    if (dataItem.Name != "FAI_RANDOM_SAMPLE")
                    {
                        //标准值
                        double standardValue = double.Parse(Common.pointCheckTable.Rows[measureProduct.whichBlock][dataItem.Name].ToString());
                        int Nol = Convert.ToInt32(Convert.ToDouble(Common.pointCheckTable.Rows[5][dataItem.Name]) * 10000 / 2);
                        int num = random.Next(-Nol, Nol);
                        dataItem.Value = Math.Round(standardValue + (double)num / 10000, 4);
                    }
                }
            }

            JUDGEMENT_RESULT ret = JUDGEMENT_RESULT.OK;//OK
            foreach (DataItem dataItem in measureProduct.MeasureData)
            {
                foreach (MeasureSize measureSize in measureSizeList)
                {
                    if (dataItem.Name == measureSize.SizeName)
                    {
                        //如果不显示，不要上传
                        if (measureSize.IsShow)
                        {
                            if (measureSize.SizeName != "FAI_RANDOM_SAMPLE")
                            {
                                if (Math.Abs(dataItem.Value) < 999)
                                {
                                    if (IsPointCheck) dataItem.Value = Math.Abs(Math.Round((dataItem.Value - measureSize.NormValue) * measureSize.K + measureSize.NormValue + measureSize.B + measureSize.B1, 4));
                                }

                                if (!measureSize.IsJudging)
                                {
                                    dataItem.JugeResult = JUDGEMENT_RESULT.OK.ToString();
                                    break;
                                }
                                if (Math.Abs(dataItem.Value) < 999)
                                {
                                    if (dataItem.Value > measureSize.NormValue + measureSize.UpperDeviation + 0.05 * (measureSize.UpperDeviation - measureSize.LowerDeviation)
                                              || dataItem.Value < measureSize.NormValue + measureSize.LowerDeviation - 0.05 * (measureSize.UpperDeviation - measureSize.LowerDeviation))
                                    {
                                        NG_FAI += dataItem.Name + @";";
                                        dataItem.JugeResult = JUDGEMENT_RESULT.EXCEPTION.ToString();
                                        if (ret != JUDGEMENT_RESULT.NA) ret = JUDGEMENT_RESULT.EXCEPTION;
                                        break;
                                    }

                                    if (dataItem.Value <= measureSize.NormValue + measureSize.UpperDeviation && dataItem.Value >= measureSize.NormValue + measureSize.LowerDeviation)
                                    {
                                        dataItem.JugeResult = JUDGEMENT_RESULT.OK.ToString();
                                    }
                                    else
                                    {
                                        NG_FAI += dataItem.Name + @";";
                                        dataItem.JugeResult = JUDGEMENT_RESULT.NG.ToString();
                                        if (ret != JUDGEMENT_RESULT.EXCEPTION && ret != JUDGEMENT_RESULT.NA)
                                            ret = JUDGEMENT_RESULT.NG;
                                    }
                                }
                                else
                                {
                                    dataItem.JugeResult = JUDGEMENT_RESULT.NA.ToString();
                                    ret = JUDGEMENT_RESULT.NA;
                                }
                            }
                        }
                    }
                }
            }
            if (!IsExit && Common.isProductPointCheck && measureProduct.whichBlock == -1)
            {
                Common.GRRPointCheckTable.Rows.Add();
                Common.GRRPointCheckTable.Rows[Common.GRRPointCheckTable.Rows.Count - 1][0] = measureProduct.SN;
                foreach (var item in measureProduct.MeasureData)
                {
                    for (int i = 0; i < Common.GRRPointCheckTable.Columns.Count; i++)
                    {
                        if (item.Name == Common.GRRPointCheckTable.Columns[i].ColumnName)
                        {
                            Common.GRRPointCheckTable.Rows[Common.GRRPointCheckTable.Rows.Count - 1][item.Name] = item.Value;
                        }
                    }
                }
                FileUtils.SaveCSV(Common.GRRPointCheckTable, Common.pointCheckPath + @"\grr_standard_Product.csv");
            }

            if (measureProduct.SN.Contains("Error"))
            {
                ret = JUDGEMENT_RESULT.NA;
            }
            measureProduct.NG_FAI = NG_FAI;
            return ret;
        }
    }
}
